<?php
/**
 * Created by PhpStorm .
 * User: {Administrator}
 * Date: {2022/7/6 16:37}
 * Author: '树叶'
 * Email: 'ayunu@qq.com'
 * Motto Info: '理想如果不向现实做一点点屈服，那么理想也将归于尘土。'
 */

namespace app\api\model;
use think\Db;
use think\Model;
use app\api\model\Config as ConfigModel;
use app\api\model\User as UserModel;

class Cart extends Model
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    protected $name = 'goods_cart';
    // 定义时间戳字段名
    protected $createTime = '';
    protected $updateTime = '';
    protected $resultSetType = 'collection';
    // 追加属性
    protected $append = [

    ];

    /**
     * 添加
     */

    public function add($gid, $sku_id = '', $uid, $goods_num)
    {
        $result = [
            'msg'    => '',
            'status' => false,
            'data'   => [],
        ];
        $goods = Db::name('goods')->where('id',$gid)->find();

        if ($goods['spec_type'] == 0)
        {
            $sku_id = 0;
        }

        if (!$goods){
            $result['msg'] = '商品不存在';
            return $result;
        }

        $time = time();
        $data = [
            'uid' => $uid,
            'gid' => $gid,
            'sku_id'    => $sku_id,
            'goods_num' => $goods_num,
            'create_time' => $time
        ];

        if ($goods['spec_type'] == 1)
        {
            if (empty($sku_id))
            {
                $result['msg'] = '请选择商品信息';
                return $result;
            }
            $goods_item = Db::name('goods_item')->where('goods_id',$gid)->where('id',$sku_id)->find();
            if (!$goods_item)
            {
                $result['msg'] = '该商品不存在';
                return $result;
            }


            $response = Db::name('goods_cart')->insertGetId($data);
            $result['msg']    = '添加成功';
            $result['status'] = true;
            $result['data']   = $response;
            return $result;
        }
        //添加购物车
        $response = Db::name('goods_cart')->insertGetId($data);
        $result['status'] = true;
        $result['data']   = $response;
        return $result;
    }

    /**
     * 列表
     */
    public function cartlist($uid)
    {
        $usercart = Db::name('goods_cart')
            ->alias('c')
            ->field('c.id,c.gid,g.name,g.main_image,gi.image,gi.spec_value_str,g.freight,g.free_shipping,c.sku_id,gi.ordinaryprice,gi.haveprice,gi.agentprice,g.ordinaryprice g_ordinaryprice,g.haveprice g_haveprice,g.agentprice g_agentprice,c.goods_num')
            ->join('goods g','g.id = c.gid','LEFT')
            ->join('goods_item gi','gi.id = c.sku_id','LEFT')
            ->where('c.uid',$uid)
            ->order('id desc')
            ->select();

        if (!$usercart) return false;
        $UserModel = new UserModel();
        $user = $UserModel->getUserInfo($uid);
        $ConfigModel = new ConfigModel();

        foreach($usercart as $key => $val)
        {

            if ($val['sku_id'] == 0)
            {
                $val['ordinaryprice'] = $val['g_ordinaryprice'];
                $val['haveprice']     = $val['g_haveprice'];
                $val['agentprice']    = $val['g_agentprice'];
            }

            if ($user['is_vip'] == 0)
            {
                $usercart[$key]['price'] = $val['ordinaryprice'];
            }
            if ($user['is_vip'] == 1)
            {
                $usercart[$key]['price'] = $val['agentprice'] != 0 ? $val['agentprice'] : $val['haveprice'];
            }
            if ($user['is_vip'] == 2)
            {
                $agent = $ConfigModel->getAgent();
                if($user['data']['is_price'] == 1)
                {
                    $usercart[$key]['price']  = empty($val['agentprice']) || $val['agentprice'] == 0 ? bcmul($agent, $val['haveprice'], 2) : $val['agentprice'];
                }else{
                    $usercart[$key]['price'] = empty($val['agentprice']) || $val['agentprice'] == 0 ? $val['haveprice'] : $val['agentprice'];
                }
            }
            if ($user['is_vip'] == 3)
            {
                $oneAgent = $ConfigModel->getOneAgent();
                if($user['data']['is_price'] == 1)
                {
                    $usercart[$key]['price']  = empty($val['agentprice']) || $val['agentprice'] == 0 ? bcmul($oneAgent, $val['haveprice'], 2) : $val['agentprice'];
                }else{
                    $usercart[$key]['price'] = empty($val['agentprice']) || $val['agentprice'] == 0 ? $val['haveprice'] : $val['agentprice'];
                }

            }
        }
        return $usercart;
    }

    /**
     * 删除购物车
     * @param $ids 购物车id
     * @param $uid 用户ID
     */
    public function del($ids,$uid)
    {
        $where = [];
        $where['id'] = ['in',$ids];
        $where['uid'] = ['eq',$uid];
        return Db::name('goods_cart')->where($where)->delete();
    }

    /**
     * @param $id 购物车id
     * @param $type 1=加,2=减
     */
    public function change($id, $cartnum)
    {
        $result = [
            'msg'  => '',
            'data' => [],
            'status' => false,
        ];
        $cart = Db::name('goods_cart')->where('id',$id)->find();

        $time = time();
        $data = [
            'goods_num'   => $cartnum,
            'update_time' => $time
        ];

        if (!$cart)
        {
            $result['msg'] = '此订单不存在';
            return $result;
        }

        if ($cart['sku_id'])
        {
            $goodsitem = Db::name('goods_item')->where('id', $cart['sku_id'])->find();


            Db::name('goods_cart')->where('id',$id)->update($data);
        }else{
            $goods = Db::name('goods')->where('id', $cart['gid'])->find();

            Db::name('goods_cart')->where('id',$id)->update($data);
        }

        $result['status'] = true;
        $result['msg'] = '操作成功';
        return $result;
    }

    /**
     * 结算页
     * @param $ids 商品id
     * @param $type 0 立即购买 1 购物车
     * @param $uid 用户ID
     */
    public function Getsettlement($uid = '', $ids = '', $type = 0, $goods_num = 0,$share = 0,$collocation = 0,$skuid = 0)
    {
        $result = [
            'status' => false,
            'data'   => [
                'list' => [], //订单数据
                'smallclothes_amout' => 0,  //商品件数
                'user_integral' => 0,  //用户积分
                'original_price'=> 0,  //原价
                'pay_price'     => 0,  //支付价格
                'order_amout'   => 0,   //优惠
                'share'         => 0,   //是否分享
                'collocation'   => 0,   //是否搭配
                'skuid'         => $skuid   //规格id
            ],
            'msg'    => '缺少信息参数'
        ];


        if (empty($uid) || empty($ids)) return $result;

        $UserModel = new UserModel();
        $userdata = $UserModel->getUserInfo($uid); // 用户会员信息

        $result['data']['user_integral'] = $userdata['data']['score']; // 用户积分

        $ConfigModel = new ConfigModel();
        $angent   = $ConfigModel->getAgent(); //普通代理商
        $OneAgent = $ConfigModel->getOneAgent(); //超级代理商

        $num      = 0;   // 商品件数
        $yf       = 0; //订单总金额
        $original = 0; //原价

        if ($type == 1)
        {
            $where = [];
            $where['id']   = ['in',$ids];
            $where['uid']  = ['eq',$uid];
            // 查出购物车里面的商品
            $cart  = Db::name('goods_cart')
                ->where($where)
                ->select();
            $result['msg'] = '参数错误';

            if (!$cart) return $result;

            $list = [];
            //商品列表
            foreach($cart as $key=>$value)
            {
                if ($value['sku_id'])
                {
                    //获取商品规格的商品
                    $goods = Db::name('goods_item')
                        ->alias('it')
                        ->join('goods g','g.id = it.goods_id','LEFT')
                        ->field('it.id,it.goods_id,g.name,g.freight,g.free_shipping,g.free_shipping,it.spec_value_str,g.main_image,it.ordinaryprice,it.haveprice,it.agentprice')
                        ->where('it.goods_id',$value['gid'])
                        ->where('it.id',$value['sku_id'])
                        ->find();

                }else{
                    $goods = Db::name('goods')
                        ->field('id,name,freight,free_shipping,main_image,ordinaryprice,haveprice,agentprice')
                        ->where('id',$value['gid'])
                        ->find();
                }

                if ($userdata['is_vip'] == 0)
                {
                    $goods['price'] = $goods['ordinaryprice'];
                }elseif ($userdata['is_vip'] == 1){

                    $goods['price'] =$goods['agentprice'] != 0 ? $goods['agentprice'] : $goods['haveprice'];
                }elseif ($userdata['is_vip'] == 2){
                    $goods['price'] = $goods['agentprice'] != 0 ? $goods['agentprice'] : bcmul($goods['haveprice'], $angent, 2);

                }elseif ($userdata['is_vip'] == 3){
                    $goods['price'] = $goods['agentprice'] != 0 ? $goods['agentprice'] : bcmul($goods['haveprice'], $OneAgent, 2);

                }

                if ($goods['freight'] == 1)
                {
                    $yf = 1;
                }

                $goods['num'] = $value['goods_num']; //商品数
                $num += $value['goods_num']; //商品总数
                $original += bcmul($goods['price'],$value['goods_num'],2); //商品总价格
                $list[]     = $goods; //每个商品
            }

        }else{
            if ($skuid)
            {
                $list = Db::name('goods_item')
                    ->alias('it')
                    ->join('goods g','g.id = it.goods_id','LEFT')
                    ->field('it.id,it.goods_id,g.name,g.free_shipping,g.free_shipping,it.spec_value_str,it.image,it.ordinaryprice,it.haveprice,it.agentprice')
                    ->where('it.goods_id',$ids)
                    ->where('it.id',$skuid)
                    ->find(); //获取商品规格的商品
            }else{
                $list = Db::name('goods')
                    ->field('id,name,freight,free_shipping,main_image,ordinaryprice,haveprice,agentprice')
                    ->where('id',$ids)
                    ->find(); //获取商品信息
            }

            if ($userdata['is_vip'] == 0)
            {
                $list['price'] = $list['ordinaryprice'];
            }elseif ($userdata['is_vip'] == 1){
                $list['price'] = $list['agentprice'] != 0 ? $list['agentprice']  : $list['haveprice'];
            }elseif ($userdata['is_vip'] == 2){
                $list['price'] = $list['agentprice'] != 0 ? $list['agentprice'] : bcmul($list['haveprice'], $angent, 2);
            }elseif ($userdata['is_vip'] == 3){
                $list['price'] = $list['agentprice'] != 0 ? $list['agentprice'] : bcmul($list['haveprice'], $OneAgent, 2);
            }
            $num = $goods_num;
            $original = bcmul($list['price'], $num, 2);
        }

        $result['status']       = true;
        $result['msg']          = '获取成功';
        $result['data']['list'] = $list; //商品信息
        $result['data']['smallclothes_amout'] = $num; //商品总件数
        $result['data']['original_price'] = $original; //商品原价
        $result['data']['pay_price']      = $result['data']['original_price'];

        if ($collocation != 0)
        {
            $goodscoll = Db::name('goods_collocation')->where('id',$collocation)->find();
            if ($goodscoll['child_goods_sku'])
            {
                $collocation_goods= Db::name('goods_item')
                    ->alias('it')
                    ->join('goods g','g.id = it.goods_id')
                    ->field('it.id,g.name,it.goods_id,it.ordinaryprice,it.haveprice,it.agentprice')
                    ->where('it.id',$goodscoll['child_goods_sku'])
                    ->find();
            }else{

                $collocation_goods = Db::name('goods')
                    ->field('id,name,ordinaryprice,haveprice,agentprice')
                    ->where('id',$goodscoll['child_goods_id'])
                    ->find();
            }
            if ($userdata['is_vip'] == 0)
            {
                $collocation_goods['price'] = $collocation_goods['ordinaryprice'];
            }elseif ($userdata['is_vip'] == 1){

                $collocation_goods['price'] = $collocation_goods['haveprice'];
            }elseif ($userdata['is_vip'] == 2){
                $collocation_goods['price'] = $collocation_goods['agentprice'] != 0 ? $collocation_goods['agentprice'] : bcmul($collocation_goods['haveprice'], $angent, 2);
            }elseif ($userdata['is_vip'] == 3){
                $collocation_goods['price'] = $collocation_goods['agentprice'] != 0 ? $collocation_goods['agentprice'] : bcmul($collocation_goods['haveprice'], $OneAgent, 2);
            }
            $result['data']['pay_price']    = bcadd($result['data']['pay_price'],$collocation_goods['price']);

            $result['data']['pay_price']    = bcsub($result['data']['pay_price'],$goodscoll['preferential']);
            $result['data']['order_amout']  = $goodscoll['preferential'];
            $result['data']['collocation']  = $collocation;
            $result['data']['child_goods_id'] = $goodscoll["child_goods_id"];
        }

        if ($share)
        {
            $result['data']['share'] = $share;
        }
        return $result;
    }

}